package com.bf.electroplating.config.mybatis;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.bf.electroplating.login.UserContext;
import com.bf.electroplating.login.UserDetail;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * @program:
 * @description: 自动填充添加、修改时间
 * @author: Tong
 * @create: 2021-12-15 10:57
 **/
@Component
public class MybatisConfig implements MetaObjectHandler {
    /**
     * 插入时的填充策略
     *
     * @param metaObject Clinton Begin
     */
    @Override
    public void insertFill(MetaObject metaObject) {
        UserDetail user = UserContext.getUser();
        this.setFieldValByName("createTime", new Date(), metaObject);
        this.setFieldValByName("updateTime", new Date(), metaObject);
        if (user!=null) {
            this.setFieldValByName("createBy", user.getUserAccountName(), metaObject);
            this.setFieldValByName("updateBy", user.getUserAccountName(), metaObject);
            if (user.getParkId()!=null){
                this.setFieldIfExists("parkId", user.getParkId(), metaObject);
            }
            if (this.getFieldValByName("companyId", metaObject)==null && user.getCompanyId()!=null){
                this.setFieldIfExists("companyId", user.getCompanyId(), metaObject);
        }
        this.setFieldValByName("delFlag", "0", metaObject);

        }
    }

    /**
     * 更新时的填充策略
     *
     * @param metaObject Clinton Begin
     */
    @Override
    public void updateFill(MetaObject metaObject) {
        UserDetail user = UserContext.getUser();
        this.setFieldValByName("updateTime", new Date(), metaObject);
        if (user!=null) {
            this.setFieldValByName("updateBy", user.getUserAccountName(), metaObject);
            if (user.getParkId() != null) {
                this.setFieldIfExists("parkId", user.getParkId(), metaObject);
            }
            if (this.getFieldValByName("companyId", metaObject) == null && user.getCompanyId() != null) {
                this.setFieldIfExists("companyId", user.getCompanyId(), metaObject);
            }
        }
    }

    private void setFieldIfExists(String fieldName, Object value, MetaObject metaObject) {
        if (metaObject.hasGetter(fieldName)) {
            this.setFieldValByName(fieldName, value, metaObject);
        }
    }
}

